package com.probiz.estore.order.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.order.SalesOrder;
import com.probiz.estore.common.model.system.PaymentMethod;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.exception.OrderProccessFlowException;
import com.probiz.estore.order.OrderConstants;
import com.probiz.estore.order.service.OrderProcessFlowManager;
import com.probiz.estore.order.service.OrderProcessFlowNtManager;
import com.probiz.estore.order.service.SalesOrderManager;

public class OrderProcessFlowNtManagerImpl implements OrderProcessFlowNtManager {
	
	private SalesOrderManager salesOrderManager ;
	private OrderProcessFlowManager orderProcessFlowManager;


	public void setSalesOrderManager(SalesOrderManager salesOrderManager) {
		this.salesOrderManager = salesOrderManager;
	}

	public void setOrderProcessFlowManager(
			OrderProcessFlowManager orderProcessFlowManager) {
		this.orderProcessFlowManager = orderProcessFlowManager;
	}



	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.order.service.OrderProcessFlowNtManager#autoCancelUnPaidOrderForScheduling()
	 */
	public void autoCancelUnPaidOrderForScheduling() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_YEAR, -ConfigUtil.getInstance().getOrderCancelDay());
		Date dt1 = cal.getTime();
		String orderStatusString = OrderConstants.ORDER_STATUS_AWAITING_CONFIRMATION+","+OrderConstants.ORDER_STATUS_CONFIRMED+","+OrderConstants.ORDER_STATUS_HANDLING;
		String hql = "from SalesOrder o where o.paymentStatus=?  and o.paymentMethodId=? and o.createTime<? and o.orderStatus in ("+orderStatusString+")";
        Object[] paramValues = new Object[]{OrderConstants.PAYMENT_STATUS_UNPAID, OrderConstants.PAYMENT_METHOD_ONLINE, dt1};
		boolean flag = true;
		int pageSize = 10;
		int pageNo = 1;
		do {
			SearchCriteria sc = SearchCriteria.getHqlPagingInstance(hql, paramValues, pageNo, pageSize, null);
			List<SalesOrder> salesOrderList = salesOrderManager.searchByCriteria(sc);
			for (SalesOrder salesOrder : salesOrderList) {
				try {
					orderProcessFlowManager.doCancelOrder4NotPaid(salesOrder);
				} catch (OrderProccessFlowException e) {
					e.printStackTrace();
				}
			}
			if (salesOrderList.size() != pageSize) {
				flag = false;
			} else {
				++pageNo;
			}
		} while (flag);
	}

}
